package com.lzq.shiro.service.impl;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import com.lzq.shiro.service.RedisService;

@Service
public class RedisServiceImpl implements RedisService , Serializable{
	
	
	private static final long serialVersionUID = 1L;
	@Autowired
	@Qualifier("stringRedisTemplate")
	private RedisTemplate<String , ?> redisTemplate; 
	
	@Override
	public boolean set(final String key, final String value) {
		return redisTemplate.execute(new RedisCallback<Boolean>() {

			@Override
			public Boolean doInRedis(RedisConnection conn) throws DataAccessException {
				RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
				conn.set(serializer.serialize(key), serializer.serialize(value));
				return true;
			}
			
		});
	}

	@Override
	public String get(final String key) {
		
		return redisTemplate.execute(new RedisCallback<String>() {

			@Override
			public String doInRedis(RedisConnection conn) throws DataAccessException {
				RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
				byte[] value = conn.get(serializer.serialize(key));
				return serializer.deserialize(value);
			}
			
		});
	}
	
	
}
